#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <time.h>

int number = 0;

// 定义一读写锁
pthread_rwlock_t rwlock;


void* trd_write(void* arg) {
    int i = *(int*)arg;   // 解引用

    int cur;
    while(1) {
        pthread_rwlock_wrlock(&rwlock);
        cur = number;
        cur++;
        number = cur;

        printf("[%d] - W: [%d]\n", i, cur);
        pthread_rwlock_unlock(&rwlock);

        sleep(rand()%3);
    }
}

void* trd_read(void* arg) {
    int i = *(int*)arg;
    int cur;

    while(1) {
        pthread_rwlock_rdlock(&rwlock);
        cur = number;

        printf("[%d]-R: [%d]\n", i, cur);
        pthread_rwlock_unlock(&rwlock);
        sleep(rand() % 3);
    }

}

int main()
{
    srand((unsigned int)time(NULL));

    int i = 0;
    int a[8];
    pthread_t trd[8];
    
    pthread_rwlock_init(&rwlock, NULL);    

    // 创建 3 给写线程
    for(i = 0; i < 3; i++) {
        a[i] = i;
        pthread_create(&trd[i], NULL, &trd_write, &a[i]);
    }

    // 创建 5 个读线程
    for(i = 3; i < 8; i++) {
        a[i] = i;
        pthread_create(&trd[i], NULL, &trd_read, &a[i]);
    }

    for(int j = 0; j < 8; j++) {
        pthread_join(trd[j], NULL);
    }

    pthread_rwlock_destroy(&rwlock);

    return 0;
}

